<?php

/**
 *    礼品卡控制器
 *
 *    @author    yanghj
 *    @date    2014.12.02
 */
class PointcardApp extends BackendApp
{

    function index()
    {

        $conditions = $this->_get_query_conditions(array(array(
                'field' => 'is_valid',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'use_status',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'card_id',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'card_sn',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
            'field' => 'denomination',
            'equal' => '=',
            'type'  => 'numeric',
            ),array(
                'field' => 'use_range',
                'equal' => '=',
            ),array(
            'field' => 'batch_no',
            'equal' => '=',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
            'field' => 'effective_time',
            'name'  => 'effective_time_from',
            'equal' => '>=',
            'handler'=> 'gmstr2time',
            ),array(
                'field' => 'effective_time',
                'name'  => 'effective_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            )
        ));
        $model_pointcard =& m('pointcard');
        $page   =   $this->_get_page(10);    //获取分页信息
        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort  = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order,array('asc','desc')))
            {
             $sort  = 'card_id';
             $order = 'desc';
            }
        }
        else
        {
            $sort  = 'card_id';
            $order = 'desc';
        }
        $pointcards = $model_pointcard->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit'         => $page['limit'],  //获取当前页的数据
            'order'         => "$sort $order",
            'count'         => true           //允许统计
        ));
        $cfg_pointcard = $this->_get_cfg_msg();//配置文件

        $page['item_count'] = $model_pointcard->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->assign('cfg_pointcard', $cfg_pointcard);
        $this->assign('batch_no_list', $this->_get_batch_no());
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->assign('pointcards', $pointcards);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('pointcard.index.html');
    }

    function export()
    {

        $conditions = $this->_get_query_conditions(array(array(
            'field' => 'is_valid',
            'equal' => '=',
            'type'  => 'numeric',
        ),
            array(
                'field' => 'use_status',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'card_id',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'card_sn',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'denomination',
                'equal' => '=',
                'type'  => 'numeric',
            ),array(
                'field' => 'use_range',
                'equal' => '=',
            ),array(
                'field' => 'batch_no',
                'equal' => '=',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            ),array(
                'field' => 'effective_time',
                'name'  => 'effective_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),array(
                'field' => 'effective_time',
                'name'  => 'effective_time_to',
                'equal' => '<=',
                'handler'   => 'gmstr2time_end',
            )
        ));
        $model_pointcard =& m('pointcard');

        $cfg_pointcard = $this->_get_cfg_msg();//配置文件

        //导出数据
        $export_pointcards = $model_pointcard->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'order'         => "card_id asc",
        ));
        if($export_pointcards)
        {

            if(count($export_pointcards) > 10000){
                echo "<script>alert('数据量不能大于10000，请筛选查询分批导出');history.back();</script>";
            }
            else
            {
                $keys = array_keys($export_pointcards);
                $ids = implode(',', $keys);

                foreach($export_pointcards as $key=>$val)
                {
                    $export_pointcards[$key]['add_time'] = date('Y-m-d',$export_pointcards[$key]['add_time']);
                    $export_pointcards[$key]['valid_time'] = date('Y-m-d',$export_pointcards[$key]['valid_time']);
                    $export_pointcards[$key]['purpose'] = $cfg_pointcard['purpose'][$export_pointcards[$key]['purpose']];
                    $export_pointcards[$key]['use_status'] = $cfg_pointcard['use_status'][$export_pointcards[$key]['use_status']];
                    $export_pointcards[$key]['is_valid'] = $cfg_pointcard['valid'][$export_pointcards[$key]['is_valid']];
                    $export_pointcards[$key]['use_range'] = $cfg_pointcard['use_range'][$export_pointcards[$key]['use_range']];
                }
                $first_arr = reset($export_pointcards);
                $end_arr = end($export_pointcards);
                $msg = '导出礼品卡：卡ID'.$first_arr['card_id'].'-'.$end_arr['card_id'].'共'.count($keys).'张卡';
                $this->admin_log($msg);
                $heads = $this->_get_excel_heads();
                require(ROOT_PATH."/includes/PHPExcel/export_excel.php");
                createExcel('礼品卡', $heads, $export_pointcards);
                exit;
            }

        }
    }

    function add()
    {

        if (!IS_POST)
        {
            $cfg_pointcard = $this->_get_cfg_msg();
            $this->assign('cfg_pointcard' , $cfg_pointcard);
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
            $this->display('pointcard.form.html');
        }
        else
        {
            $model_pointcard =& m('pointcard');
            $max_id = $model_pointcard->getOne("SELECT MAX(card_id) FROM {$model_pointcard->table}");
            $max_id = !empty($max_id)?intval($max_id):0;
            $data = array();
            $batch_no       =   html_script(trim($_POST['batch_no']));
            $create_number    =   intval($_POST['create_number']);
            $denomination     =   intval($_POST['denomination']);
            $valid_time       =   html_script(trim($_POST['valid_time']));
            $purpose          =   intval($_POST['purpose']);
            $use_range        =   html_script(trim($_POST['use_range']));
            $add_time         =   gmtime();
            if($create_number<1 && $create_number>10000)
            {
                $this->show_warning("生成数量不正确!");
            }
            for($i=0;$i<$create_number;$i++)
            {
                $data[$i]['batch_no']     =   $batch_no;
                $data[$i]['card_sn']     =   $this->_create_card_sn($use_range,$max_id+$i+1);
                $data[$i]['raw_password']     =   $this->_get_rand_char(16);
                $data[$i]['password']     =   md5($data[$i]['raw_password']);
                $data[$i]['denomination']     =   $denomination;
                $data[$i]['valid_time']       =   strtotime($valid_time);
                $data[$i]['purpose']          =   $purpose;
                $data[$i]['use_range']        =   $use_range;
                $data[$i]['add_time']         =   $add_time;
            }

            if (!$model_pointcard->add($data))
            {
                $this->show_warning($model_pointcard->get_error());
                return;
            }
            $msg = '添加礼品卡：卡号从'.$data[0]['card_sn'].'-'.$data[$create_number-1]['card_sn'].'共'.$create_number.'张卡';
            $this->admin_log($msg);

            $this->show_message('add_pointcard_successed',
                'back_list',    'index.php?app=pointcard'
            );
        }
    }

    function edit()
    {

        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id)
        {
            $this->show_warning('no_pointcard');
            return;
        }
        $data = array();
        if(isset($_GET['is_valid']))
        {
            $data['is_valid'] = intval($_GET['is_valid']);
            $data['effective_time'] = intval($_GET['is_valid']) == 1 ? gmtime() : 0;
        }

        if(isset($_GET['valid_time']))
        {
            if($_GET['valid_time']<date('Y-m-d'))
            {
                $this->show_warning('卡有效日期错误');
                return;
            }
            $data['valid_time'] =  strtotime(trim($_GET['valid_time']));
        }

        if(!$data)
        {
            $this->show_warning('no_pointcard');
            return;
        }


        $model_pointcard =& m('pointcard');

        $ids = explode(',', $id);

        $model_pointcard->edit($ids, $data);
        if ($model_pointcard->has_error())
        {
            $this->show_warning($model_pointcard->get_error());
            return;
        }
        if(intval($_GET['is_valid']) == 1)
        {
            $msg = '确认生效礼品卡：卡ID'.$id.'共'.count($ids).'张卡';
        }
        if(intval($_GET['is_valid']) == 2)
        {
            $msg = '确认废止礼品卡：卡ID'.$id.'共'.count($ids).'张卡';
        }
        if(isset($_GET['valid_time']))
        {
            $msg = '重新设置有效期礼品卡：卡ID'.$id.'共'.count($ids).'张卡,有效期为'.$_GET['valid_time'];
        }
        $this->admin_log($msg);

        $this->show_message('操作成功!');
    }

    function activate()
    {
        $change_time_from = !empty($_GET['change_time_from']) ? gmstr2time($_GET['change_time_from']) : gmstr2time(date('Y-m-d',strtotime('-2 month')));
        $change_time_to = !empty($_GET['change_time_to']) ? gmstr2time_end($_GET['change_time_to'])-1 : time();
        $conditions = "change_time >= {$change_time_from} AND change_time <= {$change_time_to} AND change_type = 3 AND user_id <> 4";
        $model_accountlog =& m('accountlog');
        $sql = "SELECT FROM_UNIXTIME(change_time,'%Y-%m-%d') as day,count(log_id) as num from {$model_accountlog->table} where {$conditions} group by day order by day desc";

        $pointcards = $model_accountlog->getAll($sql);
        //$this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->assign('pointcards', $pointcards);
        $this->assign('change_time_from', $change_time_from);
        $this->assign('change_time_to', $change_time_to);
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('pointcard.activate.html');
    }

    function view()
    {
        $date = trim($_GET['date']);
        $conditions = "FROM_UNIXTIME(a.change_time,'%Y-%m-%d')= '{$date}' AND a.change_type = 3 AND a.user_id <> 4";
        $model_accountlog =& m('accountlog');
        $sql = "SELECT FROM_UNIXTIME(a.change_time,'%Y-%m-%d') as day,a.order_no,m.user_name,s.store_name from {$model_accountlog->table} AS a left join ".DB_PREFIX."member AS m on a.user_id=m.user_id left join ".DB_PREFIX."store AS s on a.user_id=s.store_id where {$conditions}";
        $pointcards = $model_accountlog->getAll($sql);

        $this->assign('pointcards', $pointcards);
        $this->display('pointcard.view.html');
    }

    /*
     * 根据不同适用范围生成礼品卡号
     */
    function _create_card_sn($use_range,$card_id)
    {
        $temp_num = 1000000000;
        if($card_id<$temp_num)
        {
            $new_num = $card_id + $temp_num;
            $real_num = $use_range.substr($new_num,1,9); //即截取掉最前面的“1”
        }
        else
        {
            $real_num = $use_range.$card_id;
        }
        return $real_num;
    }
    /*
     * 生成长度为$length随机数
     */
    function _get_rand_char($length = 16){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    /*
     * 获取批次号
     */
    function _get_batch_no(){

        $arr = array();
        $model_pointcard =& m('pointcard');

        $data = $model_pointcard->find(array(
            'conditions' => '1 GROUP BY batch_no',
            'fields' => 'batch_no',
        ));
        if($data)
        {
            foreach($data as $key => $val)
            {
                $arr[$val['batch_no']] = $val['batch_no'];
            }
        }

        return $arr;
    }

    function _get_excel_heads()
    {
        return array(
            'card_id' => array('name' => "商品编号" ),
            'card_sn' => array('name' => "卡号" ),
            'raw_password' => array('name' => "密码"),
            'denomination' => array('name' => "面值"),
            'add_time' => array('name' => "生成日期"),
            'valid_time' => array('name' => "有效日期"),
            //'purpose' => array('name' => "卡用途"),
            //'use_range' => array('name' => "适用范围"),
            //'use_status' => array('name' => "使用状态"),
            //'is_valid' => array('name' => "是否生效"),
        );
    }

    /**
     * 礼品卡配置信息
     */
    function _get_cfg_msg()
    {
        $cfg_pointcard = array(
            'denomination' =>array(
                '100' => 100,
                '200' => 200,
                '500' => 500,
                '1000' => 1000,
                '5000' => 5000,
            ),
            'purpose' =>array(
                '1' => '全部',
                '2' => '赠送',
                '3' => '直销',
                '4' => '分销',
            ),
            'use_range' =>array(
                '001' => '全网',
                '002' => '平安保险专区',
                '003' => '电信专区',
                '004' => '移动专区',
                '005' => '中意人寿专区',
            ),
            'is_valid' =>array(
                '0' => '未生效',
                '1' => '生效',
                '2' => '废止',
            ),
            'valid' =>array(
                '0' => '未生效',
                '1' => '生效',
                '2' => '废止',
            ),
            'use_status' =>array(
                '0' => '未使用',
                '1' => '已使用',
            ),
        );
        return $cfg_pointcard;
    }
}
?>
